package com.example.security.demo.config;


import com.sun.org.apache.xml.internal.resolver.readers.ExtendedXMLCatalogReader;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;


//配置类
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception{
        http
                .formLogin()
                .usernameParameter("username123")  //我们自己写的登录页面的用户名的name属性值必须是这个配置的,不然就是默认的username
                .passwordParameter("password12")  //同上
                .loginProcessingUrl("/login")  //这个/login是我们自定义的登录页面的提交地址
                .loginPage("/login.html")
                .successForwardUrl("/toMain")//自定义登录页面  登录成功后跳转页面必须是post请求
                .failureForwardUrl("/toError");  //登录失败后也是post请求
        //antMatchers("/login.html").permitAll() 登录页面放行
        //anyRequest().authenticated() 所有请求都必须认证, 必须登录之后被访问
        http
                .authorizeHttpRequests()
                .antMatchers("/login.html").permitAll()
                .antMatchers("/error.html").permitAll()
                .anyRequest()
                .authenticated();

        http.csrf().disable();   //关闭csrf防护
    }

    @Bean
    public PasswordEncoder getPw(){
        return new BCryptPasswordEncoder();
    }
}
